package org.example.day12;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 4.1.16 使用condition实现顺序执行
 **/
public class MyThread3 {
    volatile private static int who = 1;
    private static ReentrantLock lock = new ReentrantLock();
    final private static Condition conditionA = lock.newCondition();
    final private static Condition conditionB = lock.newCondition();
    final private static Condition conditionC = lock.newCondition();

    public static void main(String[] args) {
        Thread ta = new Thread(){
            @Override
            public void run() {
                try {
                    lock.lock();
                    while(who != 1){
                        conditionA.await();
                    }
                    for (int i = 0; i < 3; i++) {
                        System.out.println("ThreadA " + (i+1));
                    }
                    who = 2;
                    conditionB.signalAll();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        };
        Thread tb = new Thread(){
            @Override
            public void run() {
                try {
                    lock.lock();
                    while(who != 2){
                        conditionB.await();
                    }
                    for (int i = 0; i < 3; i++) {
                        System.out.println("ThreadB " + (i+1));
                    }
                    who = 3;
                    conditionC.signalAll();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        };
        Thread tc = new Thread(){
            @Override
            public void run() {
                try {
                    lock.lock();
                    while(who != 3){
                        conditionC.await();
                    }
                    for (int i = 0; i < 3; i++) {
                        System.out.println("ThreadC " + (i+1));
                    }
                    who = 1;
                    conditionA.signalAll();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        };
        Thread[] threadsA = new Thread[5];
        Thread[] threadsB = new Thread[5];
        Thread[] threadsC = new Thread[5];
        for (int i = 0; i < 5; i++) {
            threadsA[i] = new Thread(ta);
            threadsB[i] = new Thread(tb);
            threadsC[i] = new Thread(tc);
            threadsA[i].start();
            threadsB[i].start();
            threadsC[i].start();
        }
    }
}
